//
//  XJBrokenLineView.m
//  Demo-折线王者
//
//  Created by Silent on 14/10/28.
//  Copyright (c) 2014年 MLF.YiLiao. All rights reserved.
//

#import "XJBrokenLineView.h"
#import "XJGraphLine.h"
#import "UIView+IM.h"

/** 各种的小间隔数据 */

/** 横轴的宽度 */
#define XJBrokenLineYaxisWidth      0.4
#define XJBrokenLineXaxisWidth      0.4
#define XJBrokenLineWidth           1.5

/** 横轴线颜色 */
#define XJHorizontalLineColor      [UIColor lightGrayColor]
#define XJVerticalLineColor        [UIColor lightGrayColor]

/** 各种字体大小 */
#define XJValueFontSize           [UIFont systemFontOfSize:8.0]

/** x轴坐标的字体 */
#define XJxAxisFontSize           15.0
#define XJxAxisFontName           @"Helvetica"

@interface XJBrokenLineView ()
{
    /** 每个间隔的数值 */
    int _yPadding;
    /** 线的个数 */
    int _numLine;
    /** 画的次数 */
    int _drawTimes;
}
/** 所有的线 */
@property (strong, nonatomic) NSMutableArray *allGraphLine;

/** 线上的值 */
@property (strong, nonatomic) NSMutableArray *allValueLabel;


/** X值集合 */
@property (strong, nonatomic) NSArray *xAxisValues;
/** 坐标原点 */
@property (assign, nonatomic) CGPoint originPoint;

/** 横轴线的间距 */
@property (assign, nonatomic) float yAxisLineInterval;
/** 纵轴线的间距 */
@property (assign, nonatomic) float xAxisLineInterval;
/** Y轴方向的数据个数 */
@property (assign, nonatomic) int numberOfHorizontal;
/** y坐标的字体 */
@property (strong, nonatomic) UIFont *yAxisLabelFont;

/** 定时器 */
@property (strong, nonatomic) NSTimer *timer;
/** 定时器重复次数 */
@property (assign, nonatomic) int repeatedCount;

/** 标准线 */
@property (strong, nonatomic) UIView *standardLine;

@end
@implementation XJBrokenLineView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置折线图的属性
        [self setupCommon];
    }
    return self;
}

- (void)setupCommon
{
    // 默认数据 all可以修改
    self.originPoint = CGPointMake(25, 20);
    self.numberOfHorizontal = 5;
    self.yAxisLineInterval = 40;
    self.yAxisLabelFont = [UIFont systemFontOfSize:10.0];
    self.standardLineWidth = 1.2;
    _drawTimes = 0;
    
}

#pragma mark - 开始绘图
- (void)startDrawLine
{
    self.repeatedCount = 0;
    // 实例定时器
    //[self timer];
    // 原点坐标
    if ([self.delegate respondsToSelector:@selector(brokenLineViewWithoriginPoint:)]) {
        self.originPoint = [self.delegate brokenLineViewWithoriginPoint:self];
    }

    // Y轴间隔
    if ([self.delegate respondsToSelector:@selector(brokenLineViewWithIntervalForyAxisLine:)]) {
        self.yAxisLineInterval = [self.delegate brokenLineViewWithIntervalForyAxisLine:self];
    }
    
    // Y轴数值个数
    if ([self.delegate respondsToSelector:@selector(brokenLineViewWithNumberOfHorizontal:)]) {
        self.numberOfHorizontal = [self.delegate brokenLineViewWithNumberOfHorizontal:self];
    }
    
    // 确定线条的个数
    if ([self.dataSource respondsToSelector:@selector(numberOfLineInBrokenLineView:)]) {
        _numLine = [self.dataSource numberOfLineInBrokenLineView:self];
    }
    // 确定线条的属性
//    [self removeAllGraphLine];
    
    NSMutableArray *arrayM = [NSMutableArray array];
    
    for (int i = 0; i < _numLine; i++) {
        if ([self.dataSource respondsToSelector:@selector(brokenLineView:withNumberForLine:)]) {
            XJGraphLine *line = [self.dataSource brokenLineView:self withNumberForLine:i];
            
            [self addLineWithLineAttribute:line WithArray:arrayM];
//            [arrayM addObject:line];
        }
    }
    self.allGraphLine = arrayM;
    // 确定横坐标的值
    if ([self.dataSource respondsToSelector:@selector(brokenLineViewWithXAxisValues:)]) {
        self.xAxisValues = [self.dataSource brokenLineViewWithXAxisValues:self];
    }
    NSLog(@"statrtsssssssssssssssssssss");
    // 开始绘制
    [self.timer fire];
    _drawTimes++;
}

#pragma mark - 定时器
- (void)toDoDrawLine
{
    if (self.repeatedCount >= self.xAxisValues.count) {
        [self.timer invalidate];
        NSLog(@"%d", self.repeatedCount);
        self.timer = nil;
        return;
    }
    self.repeatedCount++;
    [self setNeedsDisplay];
}

#pragma mark - 核心绘图
- (void)drawRect:(CGRect)rect
{
    // 当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 设置虚线时的格式
    CGFloat lengths[] = {10,10};
    // 创建变换设置的文本矩阵
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    
    // draw yAxis
    /** 个数 */
    int yAxisNum = self.numberOfHorizontal;
    /** Y 轴真实间隔 */
    float yAxisLineInterval = self.yAxisLineInterval;
    
    
    //NSLog(@"ynum is %d",yAxisNum);
    
    
    //NSLog(@"y is %f",yAxisLineInterval);

    /** 坐标原点 */
    CGPoint point = self.originPoint;
    for (int i = 0 ; i <yAxisNum; i++) {
              float height = yAxisLineInterval * i;
        /** 横标准线的y变量 */
        float yCoordinate = self.height - point.y - height;
        
        // 线宽
        CGContextSetLineWidth(context, XJBrokenLineYaxisWidth);
        // 线色
        [XJHorizontalLineColor set];
        
        // 移动到左边的原点
        CGContextMoveToPoint(context, point.x, yCoordinate);
        // 划线 第一条线直线
        CGContextAddLineToPoint(context, self.width, yCoordinate);
        CGContextStrokePath(context);
        
        // 设置为虚线
        CGContextSetLineDash(context, 0, lengths, 2);
        CGContextStrokePath(context);
        
        // 设置值
        CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
        // 字符
        NSString *yLabel = [NSString stringWithFormat:@"%d",_yPadding *i];
        NSInteger yNumber = [yLabel lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        // 设置 字体的格式 字体的大小
        float yAxisFontSize = XJxAxisFontSize;
        
        if (i > 0) {
            CGContextSelectFont(context,[XJxAxisFontName UTF8String], yAxisFontSize, kCGEncodingMacRoman);
            CGContextShowTextAtPoint(context, 0, yCoordinate+5, [yLabel UTF8String], yNumber);
        }
//        UILabel *label = [[UILabel alloc] init];
//        label.frame = CGRectMake(0, yCoordinate -10, point.x, 20);
//        label.font = self.yAxisLabelFont;
//        NSString *yLabel = [NSString stringWithFormat:@"%d",_yPadding *i];
//        label.textAlignment = NSTextAlignmentCenter;
//        if (i > 0) {
//            label.text = yLabel;
//        }
//        label.textColor = XJHorizontalLineColor;
//        [self addSubview:label];
    }
    
    // draw xAxis
    int xAxisNum = (int)self.xAxisValues.count;
    for (int i = 0; i < xAxisNum; i++) {
        float verticalX = point.x + self.xAxisLineInterval * i;
        // 划线
        [XJVerticalLineColor set];
        // 设置线宽
        CGContextSetLineWidth(context, XJBrokenLineXaxisWidth);
        // 设置为实线
        if (i == 0) {
            CGContextSetLineDash(context, 0, nil, 0);
        }
        CGContextMoveToPoint(context, verticalX, self.height- point.y);
        CGContextAddLineToPoint(context, verticalX, 0);
        CGContextStrokePath(context);
        
        // 虚线
        CGContextSetLineDash(context, 0, lengths, 2);
        CGContextStrokePath(context);

        CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
        // 字符
        NSString *numString = [NSString stringWithFormat:@"%@",self.xAxisValues[i]];
        NSInteger hhhh = [numString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        
        // 设置 字体的格式 字体的大小
        float xAxisFontSize = XJxAxisFontSize;
        CGContextSelectFont(context,[XJxAxisFontName UTF8String], xAxisFontSize, kCGEncodingMacRoman);
        CGContextShowTextAtPoint(context, verticalX -5, self.height -5, [numString UTF8String], hhhh);
    }
    
    // draw lines
    // 每个点代表的数值
    float perValue = _yPadding / self.yAxisLineInterval;
    for (int j = 0; j < _numLine; j++) {
        
        // 取出所有值
        XJGraphLine *graphLine = self.allGraphLine[j];
        NSArray *yAxisValues = graphLine.yAxisValues;
        int count = self.repeatedCount;
        if (self.repeatedCount >= yAxisValues.count) {
            count = (int)yAxisValues.count;
        }
        for (int i = 0; i < count; i++) {
            // 取出值
            float value = [yAxisValues[i] floatValue];
            
            float valueX = point.x + self.xAxisLineInterval * i + self.xAxisLineInterval;
            float valueY = self.height - point.y - (value / perValue);
            
            if (i == 0) {
                CGContextMoveToPoint(context, valueX, valueY);
            }else
            {
                CGContextAddLineToPoint(context, valueX, valueY);
            }
            // 添加按钮
            if (i == count-1 && self.repeatedCount==count) {
                    if ((self.allValueLabel.count < yAxisValues.count * _numLine)) {
                        UIButton *btn = [[UIButton alloc] init];
                        NSString *str = [NSString stringWithFormat:@"%@",yAxisValues[i]];
                        [btn setTitle:str forState:UIControlStateNormal];
                        
                        btn.titleLabel.font = [UIFont fontWithName:XJxAxisFontName size:8];
                        [btn setTitleColor:graphLine.valueColor forState:UIControlStateNormal];
                        [btn setTitleColor:graphLine.lightValueColor forState:UIControlStateSelected];
                        btn.titleLabel.numberOfLines = 0;
                        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
                        [self.allValueLabel addObject:btn];
                        [self addSubview:btn];
                    }
                int dex = _numLine * (self.repeatedCount-1) + j;
                UIButton *btn = self.allValueLabel[dex];
                btn.size = CGSizeMake(self.xAxisLineInterval -4, 18);
                btn.center = CGPointMake(valueX, valueY- 5);
            }
        }
        // 设置属性
        [graphLine.lineColor set];
        CGContextSetLineWidth(context, graphLine.lineWidth);
        // 设置为实线
        CGContextSetLineDash(context, 0, nil, 0);
        CGContextStrokePath(context);
    }
}

#pragma mark - 添加线
- (void)addLineWithLineAttribute:(XJGraphLine *)graphLine WithArray:(NSMutableArray *)array
{
    NSArray *yAxisValues = graphLine.yAxisValues;
    float max = [[yAxisValues valueForKeyPath:@"@max.floatValue"] floatValue];
    
    // 为了取整值
    int maxY = ((int)(max + 0.2 * max) / 10 ) * 10;
    int yperValue = ((maxY / (5 * self.numberOfHorizontal)) + 1 ) * 5;
    
    float xInterval = (self.width - self.originPoint.x * 2) / yAxisValues.count;
    self.xAxisLineInterval = xInterval;
    _yPadding = yperValue > _yPadding ? yperValue:_yPadding;
    [array addObject:graphLine];
}

- (void)removeLineWithGraphLine:(XJGraphLine *)graphLine
{
    for (UIButton *btn in graphLine.allValueLabel) {
        [btn removeFromSuperview];
    }
    [self.allGraphLine removeObject:graphLine];
}

- (void)removeAllGraphLine
{
    for (XJGraphLine *line in self.allGraphLine) {
        [line removeAllValueLabel];
    }
}

#pragma mark - 懒加载
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(toDoDrawLine) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (NSMutableArray *)allGraphLine
{
    if (!_allGraphLine) {
        _allGraphLine = [NSMutableArray array];
    }
    return _allGraphLine;
}

- (UIView *)standardLine
{
    if (!_standardLine) {
        _standardLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.standardLineWidth, self.height - self.originPoint.y)];
        //NSLog(@"yyyy is %f",self.originPoint.y);
        _standardLine.backgroundColor = [UIColor lightGrayColor];
    }
    return _standardLine;
}

- (NSMutableArray *)allValueLabel
{
    if (!_allValueLabel) {
        _allValueLabel = [NSMutableArray array];
    }
    return _allValueLabel;
}

#pragma mark - 手势识别
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 取点
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self];
    self.standardLine.x = point.x;
    [self addSubview:self.standardLine];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self];
    self.standardLine.x = point.x;
    for (UIButton *btn in self.allValueLabel) {
        
        if (CGRectIntersectsRect(btn.frame, self.standardLine.frame)) {
            btn.selected = YES;
            /** 选中的回调 */
            if ([self.delegate respondsToSelector:@selector(brokenLineView:didSelectBtnAtNow:)]) {
                [self.delegate brokenLineView:self didSelectBtnAtNow:btn];
            }
        }
        else
        {
            btn.selected = NO;
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.standardLine removeFromSuperview];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.standardLine removeFromSuperview];
}

@end
